//need to keep notification object for backward compatibility.
//Unfortunately I changed the database schema but was unable (likely due to my noobness)
// to perform an upgrade and data-conversion on the old database. At some point in the 
// future this code will be removed for now it's deprecated.
var notification = (function() {
	var sign;
	var who;
	var link;
	var gift;
	var crew;
	var ts;
	var txt;
	var linkId;
	var me = this;
	
	var item = function() {
		return {
			"signature": me.sign,
			"who": me.who,
			"link": me.link,
			"gift": me.gift,
			"crewed": me.crew,
			"timestamp": me.ts,
			"text": me.txt,
			"linkId": me.linkId
		};
	};
	
	var setLink = function(link) {
		var str = link;
		me.link = str;
		str = str.split('%22');
		if (str.length > 1) {
			str = str[3];
			str = base64.decode(str);
			while (String(str.substr(0, str.length - 1)).lastIndexOf('}') != -1) { str = str.substr(0, str.length - 1) }
			var obj = JSON.parse(str);
			me.gift = (obj.gift) ? obj.gift : undefined;
			me.crew = (obj.buildingName) ? obj.buildingName : undefined;
			me.ts = (obj.timestamp) ? obj.timestamp : undefined;
			me.sign = (obj.signature) ? obj.signature : undefined;
		}
	};
	
	var crudOps = (function() {
		return {
			"loadFrom": (function() {
				return {
					"html": function(htmlText) {
						var div = document.createElement('div');
						div.innerHTML = htmlText;	//load html
						
						setLink('https://plus.google.com/u/0/' + $('span.LFb > a', div).attr('href'));
						me.who = $('span.HFb > a', div).text();
						me.text = $('div.IFb > div', div).text();
						me.linkId = $('div.E7a', div).attr('link_id');
						
						return item();
					},
					"db": function(obj) {
						setLink(obj.link);
						me.who = obj.name;
						me.text = obj.text;
						
						return item();
					},
					"history": function(obj) {
						setLink(obj.link);
						me.who = obj.name;
						me.text =  obj.time;
						
						return item();
					}
				};
			}()),
			"create": function(link, who, text) {
				me.who = who;
				me.txt = text;
				
				setLink(link);
				
				return item();
			},
			"save": function(item) {
				if (item.sign) {
					$.indexedDB(DB_NAME).objectStore(NOTE_TABLE).add({ sig: item.sign, name: item.who, link: item.link, gift: item.gift, crew: item.crew, text: item.txt});
				}
			},
			"get": function(key) {
				$.indexedDB(DB_NAME).objectStore(NOTE_TABLE).get(key).done(function(val) { 
					return crudOps.loadFrom.db(val);
				});
			},
			"delete": function(callback) {
				if (me.sign) {
					$.indexedDB(DB_NAME).objectStore(NOTE_TABLE)["delete"](me.sign).done(function() {
						if (typeof callback === 'function') {
							callback();
						}
					});
				}
			},
			"print": function() {
				return this.item;
			}
		};
	}());
	
	return crudOps;
}());

var ena_item = (function() {
	var gid;
	var uname;
	var type;
	var uid;
	var ts;
	var text;
	var me = this;
	
	var DBName = NEW_DB_NAME; //"ENA_DB";
	var itemTable = "notification";
	
	var itemObj = function() {
		return {
			"gid": me.gid,
			"type": me.type,
			"uname": me.uname,
			"uid": me.uid,
			"text": me.text,
			"timestamp": me.ts
		};
	};
	
	var parseNotificationLink = function(link) {
		var str = link;
		me.link = str;
		str = str.split('%22');
		if (str.length > 1) {
			str = str[3];
			str = base64.decode(str);
			while (String(str.substr(0, str.length - 1)).lastIndexOf('}') != -1) { str = str.substr(0, str.length - 1) }
			var linkObj = JSON.parse(str);
			me.gid = (linkObj.gift) ? linkObj.gift : (linkObj.buildingName) ? linkObj.buildingName : undefined;
			me.type = (linkObj.gift) ? itemType.gift : (linkObj.buildingName) ? itemType.crew : itemType.request;
			me.ts = (linkObj.timestamp) ? linkObj.timestamp : undefined;
			me.uid = (linkObj.signature) ? linkObj.signature : undefined;
		}
	};
	
	var parseRewardLink = function(link) {
		var str = link;
		me.link = str;
		str = str.split('%22');
		if (str.length > 1) {
			str = str[3];
			str = base64.decode(str);
			while (String(str.substr(0, str.length - 1)).lastIndexOf('}') != -1) { str = str.substr(0, str.length - 1) }
			var linkObj = JSON.parse(str);
			me.gid = (linkObj.gift) ? linkObj.gift : (linkObj.buildingName) ? linkObj.buildingName : undefined;
			me.type = (linkObj.gift) ? itemType.gift : (linkObj.buildingName) ? itemType.crew : itemType.request;
			me.ts = (linkObj.timestamp) ? linkObj.timestamp : undefined;
			me.uid = (linkObj.signature) ? linkObj.signature : undefined;
		}
	}
	
	var itemType = (function() { 
		return {crew: 0, gift: 1, request: 2, coins: 3, reward: 4, send: 5, energy: 6, keys: 7}; 
	})();
	
	var crudOps = (function() {
		return {
			"loadNotifiction": (function() {
				return {
					"fromHTML": function(htmlText) {
						var div = document.createElement('div');
						div.innerHTML = htmlText;	//load html
						
						parseNotificationLink('https://plus.google.com/u/0/' + $('span.LFb > a', div).attr('href'));
						me.uname = $('span.HFb > a', div).text();
						me.text = $('div.IFb > div', div).text();
						
						return $('div.E7a', div).attr('link_id') 
					},
					"fromDB": function(obj) {
						me.gid = obj.gid;
						me.type = obj.type;
						me.ts = obj.ts;
						me.uname = obj.name;
						me.text = obj.text;
						me.uid = obj.uid;
						
						return itemObj();
					}
				}
			}()),
			"loadReward": (function() {
				return {
					"fromHTML": function(htmlText) {
						var div = document.createElement('div');
						div.innerHTML = htmlText;	//load html
						
						parseNotificationLink('https://plus.google.com/u/0/' + $('span.LFb > a', div).attr('href'));
						me.uname = $('span.HFb > a', div).text();
						me.text = $('div.IFb > div', div).text();
						
						return $('div.E7a', div).attr('link_id') 
					},
					"fromDB": function(obj) {
						me.gid = obj.gid;
						me.type = obj.type;
						me.ts = obj.ts;
						me.uname = obj.name;
						me.text = obj.text;
						me.uid = obj.uid;
						
						return itemObj();
					}
				}
			}()),
			"save": function(item) {
				if (item.uid) {
					$.indexedDB(DBName)
					.objectStore(itemTable)
					.add({gid: item.gid, type: item.type, uname: item.uname, text: item.text, timestamp: item.timestamp, uid: item.uid});
				}
			},
			"delete": function(callback) {
				if (me.uid) {
					$.indexedDB(DBName).objectStore(itemTable)["delete"](me.uid).done(function() {
						if (typeof callback === 'function') {
							callback();
						}
					});
				}
			},
			"create": function(link, uname, text) {
				me.uname = uname;
				me.text = text;
				
				parseLink(link);
				
				return itemObj();
			},
			"get": function(key) {
				$.indexedDB(DBName).objectStore(itemTable).get(key).done(function(val) { 
					return crudOps.loadFrom.db(val);
				});
			},
			"print": function(item) {
				if (item.uid) {
					return JSON.stringify(item);
				}
			},
			"type": itemType
		}
	}());
	
	return crudOps;
})();
/*

var notifications = (function () {
	var notes = [];
	var count = 0;
	var loaded = true;
	var me = this;
	
	var loadData = function(idx) {
		var def = $.Deferred();
		
		$.indexedDB(DB_NAME).objectStore(NOTE_TABLE).index(idx).each(function(elm) { 
			if (elm.key != '') { 
				notes.push(notification.loadFrom.db(elm.value)); 
			}
		}).done(function() {
			//console.log(notes);
			def.resolve(notes);
		});
		
		return def;
	};
	
	var getCount = function(callback) {
		$.indexedDB(DB_NAME).objectStore(NOTE_TABLE).count().then(function(count) { 
			if (typeof callback === 'function') {
				callback(count);
			}
		});
	};
	
	var deleteItem = function(id, callback) {
		$.indexedDB(DB_NAME).objectStore(NOTE_TABLE)["delete"](id).done(function() {
			if (typeof callback === 'function') {
				callback();
			}
		});
	};
	
	return {
		"load": function(index) {
			var noteArr = [];
			def = $.Deferred();
			
			loadData(index).then(function(data) {
				noteArr = data;
			});
			
			return {
				"sort": (function() {
					var timeSort = function(direction) {
						noteArr.sort(function(a,b) {
							if (direction == FIFO) {
								return a.timestamp - b.timestamp;
							} else {
								return b.timestamp - a.timestamp;
							}
						});
					};
					
					return {
						"timeAsc": function() {
							timeSort(FIFO);
							return noteArr;
						},
						"timeDesc": function() {
							timeSort(LIFO);
							return noteArr;
						}
					};
				}())
			};
		},
		"delete": function(id, callback) {
			deleteItem(id, callback);
			return this;
		},
		"count": function(callback) {
			return getCount(callback).then({
				
			});
		}
	};
})();*/
/*
,
		"sort": function() {
			
			return {
				"timeAsc": function() {
					return 1;
				},
				"timeDesc": function() {
					return 2;
				}
			};
		};
function sortNotifications(notificationArray) {
	var sortedNotes = [];
	var direction = globalSettings.getSetting("direction");
	
	var gifts = [];
	tmpArr = _.groupBy(notificationArray, 'gift');  	
	for (var x in tmpArr) { 
		if (x!='undefined') { 	
			if (gift_items[x]) {  
				for (var y in tmpArr[x]) { 
					gifts.push(tmpArr[x][y]);  	
				}  
			} 	
		} 	
	}
	gifts.sort(function(a,b) { 
		if (direction == FIFO) {
			return sortAscTime(a,b);
		} else {
			return sortDescTime(a,b);
		}
	});
	
	var joins = [];
	tmpArr = _.groupBy(notificationArray, 'crewed');  
	for (var x in tmpArr) { 
		if (x!='undefined') { 	
			for (var y in tmpArr[x]) {  
				joins.push(tmpArr[x][y]); 	
			} 	
		} 
	} 
	joins.sort(function(a,b) { 
		if (direction == FIFO) {
			return sortAscTime(a,b);
		} else {
			return sortDescTime(a,b);
		}
	});
	
	var reqs = []; 
	tmpArr = _.groupBy(notificationArray, 'gift');  
	for (var x in tmpArr) { 
		if (x!='undefined') { 	
			if ((req_items[x]) || (gift_items[x] == undefined)) {  	
				for (var y in tmpArr[x]) { 
					reqs.push(tmpArr[x][y]);  	
				}  
			} 	
		} 	
	} 
	reqs.sort(function(a,b) { 
		if (direction  == FIFO) {
			return sortAscTime(a,b);
		} else {
			return sortDescTime(a,b);
		}
	});
	
	//now the fun part, concat order
	// one of 6 choices 123, 132, 213, 231, 312, 321
	// 1 : GIFTS, 2 : JOINS, 3 : REQS
	switch (Number(globalSettings.getSetting("process_order_array").split(',').join(''))) {
		case 123:	//1 : GIFTS, 2 : JOINS, 3 : REQS
		default:
			sortedNotes = gifts.concat(joins, reqs);  
			break;
		case 132: //1 : GIFTS, 3 : REQS, 2 : JOINS
			sortedNotes = gifts.concat(reqs, joins);  
			break;
		case 213:  //2 : JOINS, 1 : GIFTS, 3 : REQS
			sortedNotes = joins.concat(gifts, reqs);  
			break;
		case 231:  //2 : JOINS, 3 : REQS, 1 : GIFTS
			sortedNotes = joins.concat(reqs, gifts);  
			break;
		case 312:  //3 : REQS, 1 : GIFTS, 2 : JOINS
			sortedNotes = reqs.concat(gifts, joins);  
			break;
		case 321:  //3 : REQS, 2 : JOINS, 1 : GIFTS
			sortedNotes = reqs.concat(joins, gifts);  
			break;
	}
	
	return sortedNotes;
}
*/